package agnewpct;

import java.awt.Toolkit; 
import java.awt.datatransfer.Clipboard; 
import java.awt.datatransfer.ClipboardOwner; 
import java.awt.datatransfer.DataFlavor; 
import java.awt.datatransfer.FlavorEvent; 
import java.awt.datatransfer.FlavorListener; 
import java.awt.datatransfer.Transferable; 
/** 
 * 
 * @author Rodrigo Chaves 
 * 
 */ 
public class ClipboardTextListener { 
    public void comienzaAEscuchar () { 
        Owner owner = new Owner(); 
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 
        clipboard.addFlavorListener(new CentinelaFlavor (clipboard) ); 
        Transferable contents = clipboard.getContents(owner); 
        clipboard.setContents(contents, owner); 
    } 
    class Owner implements ClipboardOwner{ 
        @Override 
        public void lostOwnership(Clipboard clipboard, Transferable contents) { 
            try {Transferable newContents = clipboard.getContents(this); 
            if (contents.getTransferData(DataFlavor.stringFlavor). 
                    equals(newContents.getTransferData(DataFlavor.stringFlavor))) 
                return; 
            clipboard.setContents(newContents, this); 
            textoHaCambiado ( (String) clipboard.getData(DataFlavor.stringFlavor)); 
            } catch (Exception e) { 
                System.out.println ("No fue texto"); //Puedes borrar esto 
            } 
        } 
    } 
    class CentinelaFlavor implements FlavorListener { 
        private Clipboard c; 
        public CentinelaFlavor (Clipboard c) { 
            this.c = c; 
        } 
        public void flavorsChanged(FlavorEvent e) { 
            try { 
                Owner o = new Owner(); 
                String nuevaString = (String) c.getContents(o).getTransferData(DataFlavor.stringFlavor); 
                c.setContents(c.getContents(o), new Owner() ); 
                textoHaCambiado ( nuevaString); 
            } catch (Exception ex) {System.out.println ("No fue texto 2");/*Puedes borrar este*/ } 
        } 
    } 
    protected void textoHaCambiado(String nuevoTexto) { 
          
    } 
}